import 'reflect-metadata';
import { Request, Response, NextFunction} from 'express';
import { get, post, controller, use } from '../decorator';
import { getResponseData } from '../utils/util';

export interface BodyRequest extends Request {
    body: { [key: string]: string | undefined }
}

export const checkLogin = (req: Request, resp: Response, next: NextFunction): void => {
    const isLogin = !!(req.session ? req.session.login : false);
    if (isLogin) {
        next();
    } else {
        resp.json(getResponseData(null, '请先登录'));
    }
}

@controller('/api')
export class LoginController {
    @get('/isLogin')
    isLogin(req: BodyRequest, resp: Response) {
        const isLogin = !!(req.session ? req.session.login : false);
        if (isLogin) {
            resp.json(getResponseData(true));
        } else {
            resp.json(getResponseData(null, '请先登录'));
        }
    }

    @post('/login')
    login(req: BodyRequest, resp: Response) {
        const { password } = req.body;
        if (password == '123') {
            if (req.session) {
                req.session.login = true;
                resp.json(getResponseData(true));
            }
        } else {
            resp.json(getResponseData(null, '密码错误'));
        }
    }

    @get('/logout')
    @use(checkLogin)
    loginout(req: BodyRequest, resp: Response) {
        if (req.session) req.session.login = undefined;
        resp.json(getResponseData(true));
    }
}